<template>
    <el-upload
            v-model:file-list="fileList"
            :action = actionUrl
            list-type="picture-card"
            :before-upload="beforeUpload"
            :on-success = onSuccess
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
    >
        <el-icon><Plus /></el-icon>
    </el-upload>

    <el-dialog v-model="dialogVisible">
        <img style="width: 100%;" :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
</template>

<script setup>
    import {onMounted,ref, reactive } from 'vue'
    import { ElMessage } from 'element-plus'

    let actionUrl = ref("")
    const dialogImageUrl = ref('')
    const dialogVisible = ref(false)
    const props = defineProps(['type','limit'])
    const emits = defineEmits(['fileList'])
    onMounted(function () {
        actionUrl.value = '/api/common/upload/' + props.type
    })

    const fileList = reactive([])

    const handleRemove = (uploadFile, uploadFiles) => {

        let temp = uploadFiles.map(e=>{return {name:e.name, url:e.response.url}})

        emits("fileList", props.type, temp)
    }

    const handlePictureCardPreview = (uploadFile) => {
        dialogImageUrl.value = uploadFile.url
        dialogVisible.value = true
    }

    function onSuccess(response, uploadFile, uploadFiles){
        ElMessage.success('上传成功!')
        fileList.push({name:uploadFile.name, url:response.data})
        emits("fileList",props.type, fileList)
    }

    const beforeUpload = (rawFile) => {
        console.log("文件格式："+rawFile.type)
        if (rawFile.type !== 'image/jpeg'
            && rawFile.type !== 'image/png'
            && rawFile.type !== 'image/gif'
            && rawFile.type !== 'image/avif') {
            ElMessage.error('必须是 JPG，PNG，gif，avif 格式!')
            return false
        } else if (rawFile.size / 1024 / 1024 > 5) {
            ElMessage.error('文件大小不能大于5MB!')
            return false
        }
        return true
    }
</script>
